import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../store";
import {
  addCarCount,
  subCarCount,
  deleteCar,
  switchCarCheck,
} from "../../store/car/carActions";
import { useCar } from "../../store/hooks";
import "./style.scss";
const Index = () => {
  const carList = useSelector((state: RootState) => state.car.carList);
  const dispatch = useDispatch();
  const { totalPrice } = useCar();

  return (
    <div className="car">
      {carList.map((v) => {
        return (
          <div className="car-item" key={v.id}>
            <input
              type="checkbox"
              checked={v.checked}
              onChange={() => dispatch(switchCarCheck(v.id))}
            />
            <dl>
              <dt>
                <img src={v.url} alt="" />
              </dt>
              <dd>
                <h3>{v.title}</h3>
                <p>￥:{v.price}</p>
                <p>
                  <button
                    onClick={() => {
                      if (v.count === 1) {
                        if (window.confirm("在减少就要删除了"))
                          dispatch(deleteCar(v.id));
                      } else {
                        dispatch(subCarCount(v.id));
                      }
                    }}
                  >
                    -
                  </button>
                  <span>{v.count}</span>
                  <button onClick={() => dispatch(addCarCount(v.id))}>+</button>
                </p>
              </dd>
            </dl>
          </div>
        );
      })}

      <h2>{totalPrice}</h2>
    </div>
  );
};

export default Index;
